package com.zrc.japktool.apk.merge;

import com.zrc.japktool.util.Zip4jUtil;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Set;

/**
 * PNG图片图片正方形缩放工具
 * 功能：在不裁剪图片的情况下，将图片缩放到到指定的正方形尺寸
 * 原理：按比例缩放到适合目标尺寸，空白部分用透明像素填充
 */
public class PicEditor {
    private String picPath;

    public PicEditor(String picPath) {
        this.picPath = picPath;
    }

    /**
     * 将输入的PNG图片缩放到指定的正方形尺寸，并返回处理后的字节数组
     * @param size 目标正方形的边长（像素）
     * @return 处理后的图片字节数组
     * @throws IOException 如果图片读写过程中发生错误
     */
    public byte[] resize( int size) throws IOException {
        // 验证目标尺寸
        if (size <= 0) {
            throw new IllegalArgumentException("目标尺寸必须是正数");
        }

        // 读取原始图片
        File inputFile = new File(picPath);
        BufferedImage originalImage = ImageIO.read(inputFile);

        if (originalImage == null) {
            throw new IOException("无法读取输入图片，请检查文件是否存在且为有效的图片格式");
        }

        // 计算缩放比例
        int originalWidth = originalImage.getWidth();
        int originalHeight = originalImage.getHeight();

        // 计算缩放比例，取宽和高中较小的比例，确保图片完全放入目标尺寸
        double scale = Math.min((double) size / originalWidth, (double) size / originalHeight);

        // 计算缩放后的尺寸
        int scaledWidth = (int) (originalWidth * scale);
        int scaledHeight = (int) (originalHeight * scale);

        // 创建缩放后的图片
        BufferedImage scaledImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = scaledImage.createGraphics();

        // 设置缩放质量
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 绘制缩放后的图片
        g2d.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
        g2d.dispose();

        // 创建目标正方形图片，背景透明
        BufferedImage squareImage = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
        Graphics2D squareG2d = squareImage.createGraphics();

        // 填充透明背景
        squareG2d.setComposite(AlphaComposite.Clear);
        squareG2d.fillRect(0, 0, size, size);
        squareG2d.setComposite(AlphaComposite.SrcOver);

        // 计算居中位置
        int x = (size - scaledWidth) / 2;
        int y = (size - scaledHeight) / 2;

        // 将缩放后的图片绘制到正方形画布中央
        squareG2d.drawImage(scaledImage, x, y, null);
        squareG2d.dispose();

        // 将处理后的图片写入字节数组，不写入文件
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(squareImage, "png", outputStream);
        return outputStream.toByteArray();
    }

    public void save2ApkFile(String outApkPath, Set<String> picPaths) throws IOException {
        if (!outApkPath.endsWith(".apk")) {
            throw new IOException(outApkPath + " 路径错误，必须以.apk结尾...");
        }
        System.out.println("正在修改图片-->" + picPaths.size());
        for (String path : picPaths) {
            if (path.contains("-ldpi")) {
                System.out.println("正在修改图片-->" + path);
                byte[] picBytes = resize(36);
                Zip4jUtil.writeFileBytes(outApkPath, path, picBytes,false);
                continue;
            }
            if (path.contains("-mdpi")) {
                System.out.println("正在修改图片-->" + path);
                byte[] picBytes = resize(48);
                Zip4jUtil.writeFileBytes(outApkPath, path, picBytes,false);
                continue;
            }
            if (path.contains("-hdpi")) {
                System.out.println("正在修改图片-->" + path);
                byte[] picBytes = resize(72);
                Zip4jUtil.writeFileBytes(outApkPath, path, picBytes,false);
                continue;
            }
            if (path.contains("-xhdpi")) {
                System.out.println("正在修改图片-->" + path);
                byte[] picBytes = resize(96);
                Zip4jUtil.writeFileBytes(outApkPath, path, picBytes,false);
                continue;
            }

            if (path.contains("-xxhdpi")) {
                System.out.println("正在修改图片-->" + path);
                byte[] picBytes = resize(144);
                Zip4jUtil.writeFileBytes(outApkPath, path, picBytes,false);
                continue;
            }
            if (path.contains("-xxxhdpi")) {
                System.out.println("正在修改图片-->" + path);
                byte[] picBytes = resize(192);
                Zip4jUtil.writeFileBytes(outApkPath, path, picBytes,false);
                continue;
            }
        }

    }

    public static void main(String[] args) {
        try {
            // 输入图片路径
            String inputPath = "C:/Users/Administrator/Desktop/test/app_icon.png";
            String outPath = "C:/Users/Administrator/Desktop/test/app_icon_out.png";

//            PicEditor picEditor = new PicEditor(inputPath, outPath);
//            byte[]  picBytes = resize(inputPath, 72);
//            Util.writeFile(picBytes,new File(outPath));
        } catch (Exception e) {
            System.err.println("处理图片时出错: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
